namespace Common;

public static class LinqExtensions
{
// 生成指定大小的数据块
    public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size)
    {
        T[] bucket = null;
        var count = 0;
        foreach (var item in source)
        {
            bucket ??= new T[size];
            bucket[count++] = item;
            if (count != size) continue;
            yield return bucket;

            bucket = null;
            count = 0;
        }

        // 返回最后一个可能未填满的桶
        if (bucket != null && count > 0)
        {
            yield return bucket.Take(count);
        }
    }
}